<?php
/**
* This will return the child nodes from the passed page.
*
* Sample returned value:
*       1"Dan Duck"Dan_Duck"false"2"Donald"Donald"true"
* Key ID, Caption, Encoded (linkable) title, has this node's children already been loaded (true or false), ... next record...
*
* @package folio
* @todo Don't include files, find a way to tap directly into the DB w/o having to bring in all of the library stuff.
*       It makes the navigation slower.
* @param int $page The parent page to display.
*/

/*
            Various properties available to calling code.
        div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
        div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
        div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
        div.innerHTML += "<li>HTTP headers: <ul>" + o.getAllResponseHeaders + "</ul></li>";
        div.innerHTML += "<li>Server response: " + o.responseText + "</li>";
        div.innerHTML += "<li>Argument object: Object ( [foo] => " + o.argument.foo +
                         " [bar] => " + o.argument.bar +" )</li>";
    */

    require_once("../../../includes.php");
    require_once("../view/page.php");
    require_once("../model/user.php");
    //require_once("../model/tree.php");

    global $CFG;

    $page = folio_page::SelectWherePageIdent( required_param('page_ident',0,PARAM_INT) );
    if( !$page ) {
        trigger_error('Invalid page_ident ' . required_param('page_ident') . ' passed to ajax/page_tree_select.php', E_USER_ERROR);
    }
    $user = folio_user::SelectWhereIdent($page->user_ident);

    $run_result = array();

    $pages = folio_page::SelectWhereParentpageIdent($page->page_ident);

    if ( $pages ) {
        foreach ($pages as $page) {
                // Load results
                if ( !folio_page::SelectWhereParentpageIdent( $page->page_ident ) ) {
                    // No kids.  Value is interpreted as 'already loaded', so since no kids, set to already loaded.
                    $expand = 'true';
                } else {
                    // Children, set loaded = false
                    $expand = 'false';
                }
                    $title = folio_PageTree::folio_tree_formattitle($page->title);
                    $link = url . $user->username . '/page/' . folio_page::title_encode($page->title);

                    $run_result[] = '"' .
                        "{$page->page_ident}`{$title}`{$expand}`{$link}`" .
                         '"';

        } // foreach
    } // if $pages

    $run_result = implode(',', $run_result);
    // "1`Tree`False`www.Tree1`"
    // Return wrapped up.
    echo <<< END
{"ResultSet":{"Result":[$run_result]}}
END;

?>
